﻿using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;

namespace tju.cme.BookStore2024.webapi.Models.Tools
{
    public class MyCustomExceptionFilter(ILogger<MyCustomExceptionFilter> logger) : IExceptionFilter
    {
        public void OnException(ExceptionContext context)
        {
            // 检查是否应该处理异常  
            if (!context.ExceptionHandled)
            {
                // 在这里可以记录日志、发送警报等  
                logger.LogInformation($"错误:{context.Exception.Message}");

                var error = new ReturnMessage()
                {
                    IsSuccess = false,
                    Message = context.Exception.Message,
                };

                // 设置HTTP响应  
                context.Result = new ObjectResult(error)
                {
                    StatusCode = StatusCodes.Status400BadRequest
                };

                // 标记异常已处理  
                context.ExceptionHandled = true;
            }
        }
    }
}
